<template>
  <a-modal
    v-model:visible="visible"
    title="新增特性"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="loading"
  >
    <a-form :model="formState" :rules="rules" ref="formRef">
      <a-form-item label="产品类型" name="productId">
        <a-select
          v-model:value="formState.productId"
          placeholder="请选择产品类型"
          @change="handleProductChange"
        >
          <a-select-option
            v-for="(label, value) in productTypeMapping"
            :key="value"
            :value="Number(value)"
          >
            {{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="特性名称" name="moduleName">
        <a-input v-model:value="formState.moduleName" placeholder="请输入特性名称" />
      </a-form-item>

      <a-form-item label="所属目录" name="parentId">
        <a-cascader
          v-model:value="formState.parentId"
          :options="treeData"
          placeholder="请选择所属目录"
          :disabled="!formState.productId"
          :fieldNames="{
            label: 'moduleName',
            value: 'featureId',
            children: 'children'
          }"
          :changeOnSelect="true"
        />
      </a-form-item>

      <a-form-item label="责任组" name="groupResponsible">
        <a-input v-model:value="formState.groupResponsible" placeholder="请输入责任组" />
      </a-form-item>

      <a-form-item label="责任人" name="personResponsible">
        <a-input v-model:value="formState.personResponsible" placeholder="请输入责任人" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { productTypeMapping } from '@/utils/productTypeMapping';
import { message } from 'ant-design-vue';
import { getFeatureTree, saveFeature } from '@/utils/api';

// 表单引用
const formRef = ref();

// 对话框可见性
const visible = ref(false);

// 加载状态
const loading = ref(false);

// 目录树数据
const treeData = ref([]);

// 表单数据
const formState = reactive({
  productId: undefined,
  moduleName: '',
  parentId: undefined,
  groupResponsible: '',
  personResponsible: ''
});

// 表单验证规则
const rules = {
  productId: [{ required: true, message: '请选择产品类型' }],
  moduleName: [{ required: true, message: '请输入特性名称' }],
  parentId: [{ required: true, message: '请选择所属目录' }],
  groupResponsible: [],
  personResponsible: [{ required: true, message: '请输入责任人' }]
};

// 产品类型变更处理
const handleProductChange = async (value: number) => {
  if (value) {
    try {
      const data = await getFeatureTree({
        productId: value
      });
      treeData.value = data;
    } catch (error) {
      message.error('获取特性树失败');
      console.error(error);
    }
  } else {
    treeData.value = [];
    formState.parentId = undefined;
  }
};

// 确认按钮处理
const handleOk = () => {
  formRef.value.validate().then(() => {
    loading.value = true;
    const parentIdValue = Array.isArray(formState.parentId) && formState.parentId.length > 0
      ? formState.parentId[formState.parentId.length - 1]
      : 0;
    const levelValue = Array.isArray(formState.parentId) ? formState.parentId.length : 1;
    saveFeature({
      productId: formState.productId || 0,
      moduleName: formState.moduleName,
      parentId: parentIdValue,
      groupResponsible: formState.groupResponsible,
      personResponsible: formState.personResponsible,
      level: levelValue
    }).then(() => {
      message.success('新增特性成功');
      loading.value = false;
      visible.value = false;
      // 重置表单
      formRef.value.resetFields();
      // 触发刷新列表事件
      emit('refresh');
    }).catch((error) => {
      message.error('新增特性失败：' + error.message);
      loading.value = false;
    });
  }).catch((error: any) => {
    console.log('验证失败:', error);
  });
};


// 取消按钮处理
const handleCancel = () => {
  formRef.value.resetFields();
  visible.value = false;
};

// 定义事件
const emit = defineEmits(['refresh']);

// 暴露方法给父组件
defineExpose({
  showModal: () => {
    visible.value = true;
  }
});
</script>